//
//  PPAbstractPictureViewController.m
//  pickpic
//
//  Created by Jinxiao on 9/17/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAbstractPictureViewController.h"

#import "PPPictureLoadingProgressView.h"

@interface PPAbstractPictureViewCell ()<UIScrollViewDelegate>
@property (readwrite, nonatomic, strong) PPPictureLoadingProgressView *progressView;
@property (readwrite, nonatomic, strong) UIImageView *statusView;

@property (nonatomic,assign) CGFloat lastScale ;

@end
const CGFloat kMaxScale = 3.0;
const CGFloat kMinScale = 1.0;
@implementation PPAbstractPictureViewCell

- (void)setArtwork:(PPAbstractArtwork *)artwork {
    _artwork = artwork;

    _pictureView.image = nil;

    [self display];
}

- (UIImage *)image {
    return _pictureView.image;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];

    self.backgroundColor = [UIColor clearColor];
    _scrollView = [[PPAbstractScrollView alloc] initWithFrame:self.bounds];
    _scrollView.backgroundColor = [UIColor clearColor];
    _scrollView.delegate = self;
    _scrollView.maximumZoomScale=kMaxScale;//最大倍率（默认倍率）
    _scrollView.minimumZoomScale=kMinScale;//最小倍率（默认倍率）
    _scrollView.decelerationRate=1.0;//减速倍率（默认倍率）
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    [self addSubview:_scrollView];

    _pictureView = [[UIImageView alloc] initWithFrame:_scrollView.bounds];
    _pictureView.contentMode = UIViewContentModeScaleAspectFit;
    _pictureView.backgroundColor = [UIColor clearColor];
    _lastScale = 1.0;
    _pictureView.userInteractionEnabled = YES;
    [_scrollView addSubview:_pictureView];
    
    UIPinchGestureRecognizer *pin = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGestureDetected:)];
    [self addGestureRecognizer:pin];
    
    
    _progressView = [[PPPictureLoadingProgressView alloc] init];
    _progressView.backgroundColor = CLEAR;
    _progressView.valueColor = [UIColor colorWithHexString:@"#A4A4B3"];
    _progressView.trackColor = [UIColor colorWithHexString:@"#F2F2F2"];
    [_pictureView addSubview:_progressView];

    _statusView = [[UIImageView alloc] init];
    _statusView.backgroundColor = [UIColor clearColor];
    _statusView.image = [UIImage imageNamed:@"shen2"];
    [self addSubview:_statusView];

    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(kProgressSize));
        make.height.equalTo(@(kProgressSize));
        make.center.equalTo(_pictureView);
    }];

    [_statusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_statusView.superview);
    }];

    UITapGestureRecognizer *stgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didRecognizeSingleTapGesture:)];
    stgr.numberOfTapsRequired = 1;
    stgr.numberOfTouchesRequired = 1;
    [self addGestureRecognizer:stgr];
    
    
    UITapGestureRecognizer *doubelGesture=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleGesture:)];
    doubelGesture.numberOfTapsRequired=2;
     stgr.numberOfTouchesRequired = 1;
    [self addGestureRecognizer:doubelGesture];
    

    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(didRecognizeLongPressGesture:)];
    [self addGestureRecognizer:lpgr];
    
     [stgr requireGestureRecognizerToFail:doubelGesture];

    return self;
}
- (void)doubleGesture:(UITapGestureRecognizer *)doubelRec{
    if (_lastScale==kMaxScale) {
        _lastScale=kMinScale;
        [_scrollView setZoomScale:_lastScale animated:YES];
        return;
    }
    if (_lastScale==kMinScale) {
        _lastScale=kMaxScale;
        [_scrollView setZoomScale:_lastScale animated:YES];
        return;
    }
    CGFloat aveScale =kMinScale+(kMaxScale-kMinScale)/2.0;//中间倍数
    if (self.lastScale>=aveScale) {
        self.lastScale=kMaxScale;
        [_scrollView setZoomScale:self.lastScale animated:YES];
        return;
    }
    if (self.lastScale<aveScale) {
        self.lastScale=kMinScale;
        [_scrollView setZoomScale:self.lastScale animated:YES];
        return;
    }
}

- (void)didRecognizeSingleTapGesture:(UITapGestureRecognizer *)stgr {
    
    PPLog(@"--- %zd",stgr.numberOfTapsRequired);
    
    [_delegate pictureViewCell:self didRecognizedSingleTapGesture:stgr];
    
    
    
    
    
}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    self.lastScale = scale;
}
- (void)didRecognizeLongPressGesture:(UILongPressGestureRecognizer *)lpgr {
    if(lpgr.state == UIGestureRecognizerStateBegan) {
        [_delegate pictureViewCell:self didRecognizedLongPressGesture:lpgr];
    }
}
- (void)layoutSubviews {
    [super layoutSubviews];

//    _scrollView.frame = self.bounds;
    _scrollView.frame = CGRectMake(0,-10, self.frame.size.width, self.frame.size.height);
    CGSize boundsSize = self.bounds.size;
    
    CGRect frameToCenter = _pictureView.frame;

    if(frameToCenter.size.width < boundsSize.width) {
        frameToCenter.origin.x = floor((boundsSize.width - frameToCenter.size.width)/2);
    } else {
        frameToCenter.origin.x = 0;
    }

    if(frameToCenter.size.height < boundsSize.height) {
        frameToCenter.origin.y = floor((boundsSize.height - frameToCenter.size.height)/2 - 64);
    } else {
        frameToCenter.origin.y = 0;
    }

    _pictureView.frame = frameToCenter;
}

- (void)prepareForReuse {
    [super prepareForReuse];

    _scrollView.frame = self.bounds;
    _scrollView.contentSize = CGSizeMake(_scrollView.width, _scrollView.height);
    //    _scrollView.maximumZoomScale = _scrollView.minimumZoomScale = _scrollView.zoomScale = 1;
    _pictureView.frame = _scrollView.bounds;
}

- (void)pinchGestureDetected:(UIPinchGestureRecognizer *)recognizer
{
    
    UIGestureRecognizerState state = [recognizer state];
    
    if(state == UIGestureRecognizerStateBegan) {
        // Reset the last scale, necessary if there are multiple objects with different scales
        _lastScale = [recognizer scale];
    }
    
    if (state == UIGestureRecognizerStateBegan ||
        state == UIGestureRecognizerStateChanged) {
        
        CGFloat currentScale = [[[recognizer view].layer valueForKeyPath:@"transform.scale"] floatValue];
        
        // Constants to adjust the max/min values of zoom

        
        CGFloat newScale = 1 -  (_lastScale - [recognizer scale]);
        newScale = MIN(newScale, kMaxScale / currentScale);
        newScale = MAX(newScale, kMinScale / currentScale);
        CGAffineTransform transform = CGAffineTransformScale([[recognizer view] transform], newScale, newScale);
        [recognizer view].transform = transform;
        _lastScale = [recognizer scale];
    }
}
- (void)reset {
    UIImage *image = _pictureView.image;

    if(image == nil) {
        return;
    }
    
    CGRect frame = CGRectMake(0, 0, self.width,self.height);

    _pictureView.frame = frame;

    _scrollView.contentSize = frame.size;

    CGFloat xscale = self.width/_pictureView.width;
    CGFloat yscale = self.height/_pictureView.height;

    CGFloat minscale = MIN(xscale, yscale);
    CGFloat maxscale = 0;

    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;

    if(_pictureView.width < width) {
        if(UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation)) {
            maxscale = height/_pictureView.width;
        } else {
            maxscale = width/_pictureView.width;
        }
    } else if(_pictureView.width > width) {
        maxscale = width/_pictureView.width;
    } else {
        maxscale = 1;
    }

    //    _scrollView.maximumZoomScale = maxscale;
    //    _scrollView.minimumZoomScale = minscale;
    //    _scrollView.zoomScale = minscale;

    CGFloat pictureWidth = _pictureView.width*minscale;
    CGFloat pictureHeight = _pictureView.height*minscale;
    _pictureView.frame = CGRectMake((_scrollView.width - pictureWidth)/2, (_scrollView.height - pictureHeight)/2, pictureWidth, pictureHeight);

    [self setNeedsLayout];
}

- (void)display {
    _progressView.hidden = YES;
    _statusView.hidden = YES;

    if(_artwork.image != nil) {
        _pictureView.image = _artwork.image;
        [self reset];
    } else if(_artwork.asset != nil) {
        _pictureView.image = _artwork.asset.image;
        [self reset];
    } else if(_artwork.URLString != nil) {
        __weak typeof(self)weakSelf = self;

        weakSelf.progressView.hidden = NO;
        
        [_artwork.URLString applyToImageView:_pictureView placeholder:nil progressive:^(double progress) {
            weakSelf.progressView.progress = progress;
        } errorCompletion:^(NSError *error) {
            weakSelf.progressView.hidden = YES;

            if(error.code == 404) {
                _statusView.hidden = NO;
            }

            [weakSelf reset];
        }];
    }
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return _pictureView;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
}

@end

@interface PPAbstractPictureViewController () <UIScrollViewDelegate, UICollectionViewDelegateFlowLayout, PPAbstractPictureViewCellDelegate>

@property (readwrite, nonatomic, assign) dispatch_once_t once;
@property (nonatomic,assign) BOOL isHiddenBar;
@end


@implementation PPAbstractPictureViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.automaticallyAdjustsScrollViewInsets = YES;
    self.edgesForExtendedLayout = UIRectEdgeTop;

    self.view.backgroundColor = [UIColor blackColor];
    self.view.clipsToBounds = YES;
    self.view.opaque = NO;

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:layout];
//    _collectionView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0);
    _collectionView.bounces = YES;
    _collectionView.alwaysBounceHorizontal = YES;
    _collectionView.pagingEnabled = YES;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_collectionView];
//    _collectionView.contentInset = [self scrollViewEdgeInsets];
    [_collectionView registerClass:[PPAbstractPictureViewCell class] forCellWithReuseIdentifier:@"cell"];

    _collectionView.contentOffset = CGPointMake(self.index*SCREEN_WIDTH, 0);
    
    [self reloadImages];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    if(self.artworks.count > 0) {
        dispatch_once(&_once, ^{
            [self scrollIndexToVisible:_index animated:NO];
        });
    }
}

- (void)reloadImages {
    [_collectionView reloadData];
}

- (void)reloadImageAtIndex:(NSInteger)index {
    [_collectionView reloadData];
    
    
}

#pragma mark - UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.artworks.count;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return collectionView.bounds.size;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PPAbstractPictureViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    PPAbstractArtwork *artwork = [self.artworks safeObjectAtIndex:indexPath.row];

    cell.delegate = self;
    cell.artwork = artwork;
    return cell;
}

- (void)scrollIndexToVisible:(NSInteger)index animated:(BOOL)animated {
    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:animated];
}

#pragma mark - PPAbstractPictureViewCellDelegate

- (void)pictureViewCell:(PPAbstractPictureViewCell *)pictureViewCell didRecognizedSingleTapGesture:(UITapGestureRecognizer *)gesture {

    

    
}

- (void)pictureViewCell:(PPAbstractPictureViewCell *)pictureViewCell didRecognizedLongPressGesture:(UILongPressGestureRecognizer *)gesture {

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    _index = (NSInteger)(scrollView.width/2 + scrollView.contentOffset.x)/scrollView.width;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self willBeginScrolling];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self didEndScrolling];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if(!decelerate) {
        [self didEndScrolling];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [self didEndScrolling];
}

- (void)willBeginScrolling {

}

- (void)didEndScrolling {

}

- (UIEdgeInsets)scrollViewEdgeInsets {
    return UIEdgeInsetsZero;
}

@end
